//
//  NetRequestTool.m
//  xiantaiApp
//
//  Created by dsy on 16/12/16.
//  Copyright © 2016年 jw. All rights reserved.
//

#import "NetRequestTool.h"
#import "LoginVC.h"
//#import "UMessage.h"
#import "LoginVC.h"

@interface NetRequestTool ()<NSURLSessionTaskDelegate>

@property (nonatomic, strong) NSURLSession *session;

@end

@implementation NetRequestTool

#pragma mark - AFHTTPSessionManager 单例方法，整个系统使用同一个AFHTTPSessionManager实例
+ (AFHTTPSessionManager *)manager {
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:sessionConfiguration];
        // 设置自定义userAgent
        // [manager.requestSerializer setValue:[self getUserAgent] forHTTPHeaderField:@"User-Agent"];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        //        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        manager.responseSerializer=[AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/json", @"text/plain",@"text/html",@"text/javascript",nil];
        //        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json", @"text/plain",nil];
        //        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        
        // 超时时间（单位秒）
        manager.requestSerializer.timeoutInterval = 30;
    });
    return manager;
}


+ (NSString *)getAbsoluteUrlNoToken:(NSString *)url {
    NSString *requestUrl = [NSString stringWithFormat:@"%@%@", BASE_URL,url];
          return requestUrl;
}

+ (NSString *)getAbsoluteUrl:(NSString *)url {
    NSString *token = [LEUserManager token];
    NSString  * version= [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    if (![CommonTTool isStrNull:token]) {

        NSString *requestUrl = [NSString stringWithFormat:@"%@%@?access_token=%@&version_no=%@&vt=1", BASE_URL,url,token,version];
        return requestUrl;
    } else {
        if (![CommonTTool isJumpLoginVC:NO]) {
            NSString *requestUrl = [NSString stringWithFormat:@"%@%@?access_token=%@&version_no=%@&vt=1", BASE_URL,url,@"jkfdlanewkh138297312nknfjdsaf",version];
            return requestUrl;
            
        }
        
        NSString *requestUrl = [NSString stringWithFormat:@"%@%@&version_no=%@&vt=1", BASE_URL, url,version];
        
        return requestUrl;
    }
}


+ (NSDictionary *)getParameterWithDict:(NSDictionary *)dict haveToken:(BOOL)isHave {
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    
    if (isHave) {
        NSString *token = [LEUserManager token];
        if (![CommonTTool isStrNull:token]) {
            [paraDict setValue:token forKey:@"access_token"];
        } else {
            [paraDict setObject:@"jkfdlanewkh138297312nknfjdsaf" forKey:@"access_token"];
        }
    }
    
    return paraDict;
}

#pragma mark - 登录接口 无token
+ (void)LoginUrl:(NSString *)url parameters:(NSDictionary *)para success:(void (^)(NSInteger statusCode, id responseObject))success failure:(void (^)(NSInteger statusCode))failure finish:(void (^)(void))finish {
    
    [CommonTTool dismisKeyBoard];
    
    AFHTTPSessionManager *manager = [self manager];
    
    // 参数
    NSDictionary *paraDict = [self getParameterWithDict:para haveToken:NO];
    
    [manager POST:[self getAbsoluteUrl:url] parameters:paraDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 返回成功
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode;
        SVPDismiss
        if (finish) {
            finish();
        }
        NSDictionary *returnDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"returnDic = %@", returnDic);
        
        // 服务器返回成功
        if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00000"]) {
            if (success) {
                success(statusCode, returnDic);
            }
     
            // 保存token
            NSString *token = [[returnDic objectForKey:@"object"] objectForKey:@"access_token"];
            if (![CommonTTool isBlankString:token]) {
                [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"access_token"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }else if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00100"]) {
            
            if (success) {
                success(statusCode, returnDic);
            }
            [self needUpdateApp];
            
        }
        else{
            if (failure) {
                failure(statusCode);
            }
            if ([returnDic[@"request_code"] isEqualToString:@"00002"]&& ![[paraDict allKeys] containsObject:@"phone"]) {
                return ;
            }
            // 判断是否access_token失效
            [self isAccess_tokenSucess:returnDic];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:returnDic];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        SVPDismiss
        if (finish) {
            finish();
        }
        if (failure) {
            failure(statusCode);
            NSLog(@"failure statusCode -- %zd", statusCode);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

#pragma mark - 通用POST请求
+ (void)postUrl:(NSString *)url parameters:(NSDictionary *)oPara success:(void (^)(id responseObject))success failure:(void (^)(NSInteger statusCode))failure finish:(void (^)(void))finish {
    
    [CommonTTool dismisKeyBoard];
    
    AFHTTPSessionManager *manager = [self manager];
    
    NSString *tempUrl = [self getAbsoluteUrl:url];
    
    // 参数
    NSDictionary *paraDict = [self getParameterWithDict:oPara];
    
    //NSLog(@"para =  %@", paraDict);
    
    if (paraDict) {
        [self matchRequestAddress:[self getAbsoluteUrl:url] andParameterDic:paraDict];
    }
    
    if ([oPara.allKeys containsObject:@"Content-Type"] ||[oPara.allKeys containsObject:@"JSON"]) { /** 表单格式特别处理 */
        manager.requestSerializer =  [AFJSONRequestSerializer serializer];
    } else {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    
//    if ([url isEqualToString:@"skuOrder/saveOrder"]) {
//        manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    }
//    
    [manager POST:tempUrl parameters:paraDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        SVPDismiss
        
        if (finish) {
            finish();
        }
        
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        //NSLog(@"url %@\n returnDic = %@",url, returnDic);
        
        
        // 服务器返回成功
        if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00000"]) {
            
            if (success) {
                success(returnDic);
            }
        }else if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00100"]) {
            if (success) {
                success(returnDic);
            }
            [self needUpdateApp];
        }
        else {
            if (failure) {
                failure([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] integerValue]);
            }
            
            // 判断是否access_token失效
            [self isAccess_tokenSucess:returnDic];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:returnDic];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        SVPDismiss
        
        if (finish) {
            finish();
        }
        
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        
        if (failure){
            failure(nil);
            NSLog(@"failure statusCode -- %zd,%@", statusCode,error);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

#pragma mark - 通用POST请求
+ (void)noTokenPostUrl:(NSString *)url parameters:(NSDictionary *)oPara success:(void (^)(id responseObject))success failure:(void (^)(NSInteger statusCode))failure finish:(void (^)(void))finish {
    
    [CommonTTool dismisKeyBoard];
    
    AFHTTPSessionManager *manager = [self manager];
    
    NSString *tempUrl = [self getAbsoluteUrlNoToken:url];
    
//    NSString *tempUrl = url;
    
    
    // 参数
    NSDictionary *paraDict = [self getParameterWithDict:oPara];
    
    NSLog(@"para =  %@", paraDict);
    
    if (paraDict) {
        [self matchRequestAddress:[self getAbsoluteUrl:url] andParameterDic:paraDict];
    }
    
    if ([oPara.allKeys containsObject:@"Content-Type"]) { /** 表单格式特别处理 */
        manager.requestSerializer =  [AFJSONRequestSerializer serializer];
    } else {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
    
//    if ([url isEqualToString:@"skuOrder/saveOrder"]) {
//        manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    }
//
    [manager POST:tempUrl parameters:paraDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        SVPDismiss
        
        if (finish) {
            finish();
        }
        
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"url %@\n returnDic = %@",url, returnDic);
        
        
        // 服务器返回成功
        if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00000"]) {
            
            if (success) {
                success(returnDic);
            }
        }
        else if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00100"]) {
            
            if (success) {
                success(returnDic);
            }
            [self needUpdateApp];
            
        }else {
            if (failure) {
                failure([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] integerValue]);
            }
            
            // 判断是否access_token失效
            [self isAccess_tokenSucess:returnDic];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:returnDic];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        SVPDismiss
        
        if (finish) {
            finish();
        }
        
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        
        if (failure){
            failure(nil);
            NSLog(@"failure statusCode -- %zd,%@", statusCode,error);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

#pragma mark - 通用POST请求
+ (void)postUrl:(NSString *)url idParameters:(id)para success:(void (^)(id responseObject))success failure:(void (^)(NSInteger statusCode))failure finish:(void (^)(void))finish {
    [CommonTTool dismisKeyBoard];
    
    AFHTTPSessionManager *manager = [self manager];
    
    NSString *tempUrl = [self getAbsoluteUrl:url];
//    if ([url isEqualToString:MatchlabeluserSave] || [url isEqualToString:MatchansweruserAnswer]) { /** 表单格式特别处理 */
//        manager.requestSerializer =  [AFJSONRequestSerializer serializer];
//    } else {
//        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    }
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager POST:tempUrl parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        SVPDismiss
        
        if (finish) {
            finish();
        }
        
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        //NSLog(@"url %@\n returnDic = %@",url, returnDic);
        
        
        // 服务器返回成功
        if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00000"]) {
            if (success) {
                success(returnDic);
            }
        }
        else if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00100"]) {
            
            if (success) {
                success(returnDic);
            }
            [self needUpdateApp];
            
        }
        else {
            if (failure) {
                failure([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] integerValue]);
            }
            
            // 判断是否access_token失效
            [self isAccess_tokenSucess:returnDic];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:returnDic];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        SVPDismiss
        
        if (finish) {
            finish();
        }
        
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        
        if (failure){
            failure(nil);
            NSLog(@"failure statusCode -- %zd,%@", statusCode,error);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

+ (void)startRequestWithUrl:(NSString *)url method:(NSString *)method params:(id)params success:(void (^)(id responseObject))success failure:(void (^)(NSInteger statusCode))failure finish:(void (^)(void))finish {
    [CommonTTool dismisKeyBoard];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSLog(@"jsonString %@",jsonString);
    
    NSString *tempUrl = [self getAbsoluteUrl:url];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    //method 为时post请求还是get请求
    NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:tempUrl parameters:nil error:nil];
    //设置超时时长
    request.timeoutInterval= 30;
    //设置上传数据type
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //设置接受数据type
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

//    NSString *token = @"123456789098765432";
//    [request setValue:token forHTTPHeaderField:@"token"];
    //将对象设置到requestbody中 ,主要是这不操作
    [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    //进行网络请求
    [[manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {

    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        SVPDismiss
        
        if (finish) {
            finish();
        }
        if (!error) {
            NSLog(@"url %@\n responseObject = %@",url, responseObject);
            
            // 服务器返回成功
            if ([[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]] isEqualToString:@"10000"]) {
                if (success) {
                    success(responseObject);
                }
            }
            else {
                if (failure) {
                    failure([[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]] integerValue]);
                }
                
                // 判断是否access_token失效
                [self isAccess_tokenSucess:responseObject];
                // 服务器返回失败 统一处理提示 外部不在显示提示
                [self managerWithErrorCode:responseObject];
            }
            
        } else {
            if (failure){
                failure(nil);
                NSLog(@"Error: %@, %@, %@", error, response, responseObject);
            }
            // 网络请求失败 统一提示
            [SVProgressHUD showInfoWithStatus:RXInternetError];
        }
    }] resume];
}

+ (NSDictionary *)getParameterWithDict:(NSDictionary *)dict {
    NSMutableDictionary *paraDict = [NSMutableDictionary dictionaryWithDictionary:dict];
    
    return paraDict;
}

+ (NSString *)matchRequestAddress:(NSString*)requestUrl andParameterDic:(NSDictionary*)parameter{
    NSString *matchStr = [NSString stringWithFormat:@"%@&",requestUrl];
    NSArray *keyArray = parameter.allKeys;
    if (keyArray.count>1) {
        for (int i=0; i<keyArray.count; i++) {
            NSString *key = [keyArray objectAtIndex:i];
            if ([[parameter objectForKey:key] isKindOfClass:[NSString class]]) {
                NSString *value = [parameter objectForKey:key];
                if (i == 0) {
                    matchStr = [matchStr stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
                } else{
                    matchStr = [matchStr stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,value]];
                }
            } else if([[parameter objectForKey:key]isKindOfClass:[NSDictionary class]]){
                if (i == 0) {
                    NSString *value = [self convertToJsonData:[parameter objectForKey:key]];
                    matchStr = [matchStr stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
                } else{
                    NSString *value = [self convertToJsonData:[parameter objectForKey:key]];
                    matchStr = [matchStr stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,value]];
                }
            }
        }
    } else{
        NSString *key = [keyArray firstObject];
        NSString *value = [parameter objectForKey:key];
        matchStr = [matchStr stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,value]];
    }
    NSLog(@"--------------最终的请求地址是%@",matchStr);
    return matchStr;
}

+ (NSString *)convertToJsonData:(NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}


+ (void)getUrl:(NSString *)url parameters:(NSDictionary *)para success:(void (^)(id))success failure:(void (^)(void))failure finish:(void (^)(void))finish {
    AFHTTPSessionManager *manager = [self manager];
    [manager GET:[self getAbsoluteUrl:url] parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SVPDismiss
        // 服务器返回成功
        if ([[responseObject objectForKey:@"status"] integerValue]==1) {
            if (success){
                success([responseObject objectForKey:@"data"]);
            }
            // 保存token
            NSString *token = [[responseObject objectForKey:@"data"] objectForKey:@"access_token"];
            if (![CommonTTool isBlankString:token]) {
                [LEUserManager setToken:token];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
        else{
            if (failure){
                failure();
            }
            
            // 判断是否access_token失效
            [self isAccess_tokenSucess:responseObject];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:responseObject];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        SVPDismiss
        if (finish) {
            finish();
        }
        if (failure){
            failure();
            NSLog(@"failure statusCode -- %zd", statusCode);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

+ (void)upLoadImage:(NSString *)url parameters:(NSDictionary *)para image:(UIImage *)image success:(void (^)(id))success failure:(void (^)(void))failure finish:(void (^)(void))finish {
    AFHTTPSessionManager *manager = [self manager];
    
    // 请求参数
    NSDictionary *paraDict = [self getParameterWithDict:para];
    
    NSLog(@"para =  %@", paraDict);
    [manager POST:[self getAbsoluteUrl:url] parameters:paraDict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        
        NSData *imageData = UIImageJPEGRepresentation(image,0.7);
        NSString *fileName = [NSString stringWithFormat:@"%.0f.jpg", [[[NSDate alloc] init] timeIntervalSince1970] * 1000];
        
        // 上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData name:@"imgFile" fileName:fileName mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        // 打印下上传进度
        SVPShowInternetWaiting
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"returnDic %@",returnDic);
        SVPDismiss
        if (finish) {
            finish();
        }
        
        // 服务器返回成功
        if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00000"]) {
            if (success){
                success(returnDic);
            }
        }
        else{
            if (failure){
                failure();
            }
            
            // 判断是否access_token失效
            [self isAccess_tokenSucess:returnDic];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:returnDic];
        }
        
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        SVPDismiss
        if (finish) {
            finish();
        }
        if (failure){
            failure();
            NSLog(@"failure statusCode -- %zd", statusCode);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

+ (void)upLoadImages:(NSString *)url parameters:(NSDictionary *)para image:(NSArray *)images success:(void (^)(id))success failure:(void (^)(void))failure finish:(void (^)(void))finish {
    
    AFHTTPSessionManager *manager = [self manager];
    
    // 请求参数
    NSDictionary *paraDict = [self getParameterWithDict:para];
    
    NSLog(@"para =  %@", paraDict);
    
    [manager POST:[self getAbsoluteUrl:url] parameters:paraDict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        // 图片
        for (UIImage *image in images) {
            NSData *imageData =UIImageJPEGRepresentation(image,0.7);
            NSString *fileName = [NSString stringWithFormat:@"%.0f.jpg", [[[NSDate alloc] init] timeIntervalSince1970]*1000];
            // 上传的参数(上传图片，以文件流的格式)
            [formData appendPartWithFileData:imageData name:@"imgFile" fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        SVPShowInternetWaiting
        // 打印下上传进度
        NSLog(@"uploadProgress %@",uploadProgress);
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        
        SVPDismiss
        // 返回成功
        if (finish) {
            finish();
        }
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"returnDic %@",returnDic);
        // 服务器返回成功
        if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00000"]) {
            if (success){
                success(returnDic);
            }
        }
        else {
            if (failure) {
                failure();
            }
            // 判断是否access_token失效
            [self isAccess_tokenSucess:returnDic];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:returnDic];
        }
        
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        SVPDismiss
        if (finish) {
            finish();
        }
        if (failure){
            failure();
            NSLog(@"failure statusCode -- %zd,%@", statusCode,error);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

#pragma mark - 上传视频
+ (void)upLoadVideo:(NSString *)url parameters:(NSDictionary *)para dataArr:(NSArray *)dataArr fileName:(NSString *)fileName success:(void (^)(id))success failure:(void (^)(void))failure finish:(void (^)(void))finish uploadProgress:(void (^)(id))progress {
    
    AFHTTPSessionManager *manager = [self manager];
    
    // 请求参数
    NSDictionary *paraDict = [self getParameterWithDict:para];
    
    NSLog(@"para =  %@", paraDict);
    
    [manager POST:[self getAbsoluteUrl:url] parameters:paraDict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        for (NSData *data in dataArr) {
           [formData appendPartWithFileData:data name:@"imgFile" fileName:fileName mimeType:@"video/mpeg"];
        }
    
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        SVPShowInternetWaiting
        // 打印下上传进度
        NSLog(@"uploadProgress %@",uploadProgress);
        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        if (progress) {
            progress(uploadProgress);
        }
        
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        SVPDismiss
        // 返回成功
        if (finish) {
            finish();
        }
        
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"returnDic %@",returnDic);
        // 服务器返回成功
        if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"status_code"]] isEqualToString:@"00000"]) {
            if (success){
                success(returnDic);
            }
        }
        else {
            if (failure) {
                failure();
            }
            // 判断是否access_token失效
            [self isAccess_tokenSucess:returnDic];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:returnDic];
        }
        
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        SVPDismiss
        if (finish) {
            finish();
        }
        if (failure){
            failure();
            NSLog(@"failure statusCode -- %zd", statusCode);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

#pragma mark - 上传文件（图片、视频）
+ (void)upLoadFile:(NSString *)url parameters:(NSDictionary *)para image:(NSArray *)images data:(NSArray *)datas fileName:(NSString *)fileName success:(void (^)(id responseObject))success failure:(void (^)(void))failure finish:(void (^)(void))finish {
    AFHTTPSessionManager *manager = [self manager];
    
    // 请求参数
    NSDictionary *paraDict = [self getParameterWithDict:para];
    
    NSLog(@"para =  %@", paraDict);
    
    [manager POST:[self getAbsoluteUrl:url] parameters:paraDict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        // 图片
        for (UIImage *image in images) {
            NSData *imageData =UIImageJPEGRepresentation(image,0.7);
            NSString *fileName = [NSString stringWithFormat:@"%.0f.jpg", [[[NSDate alloc] init] timeIntervalSince1970]*1000];
            // 上传的参数(上传图片，以文件流的格式)
            [formData appendPartWithFileData:imageData name:@"imgFile" fileName:fileName mimeType:@"image/jpeg"];
        }
        
        for (NSData *data in datas) {
            [formData appendPartWithFileData:data name:@"imgFile" fileName:fileName mimeType:@"video/mpeg"];
        }
        
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        SVPShowInternetWaiting
        // 打印下上传进度
        NSLog(@"uploadProgress %@",uploadProgress);
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        
        SVPDismiss
        // 返回成功
        if (finish) {
            finish();
        }
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"returnDic %@",returnDic);
        // 服务器返回成功
        if ([[NSString stringWithFormat:@"%@",[returnDic objectForKey:@"code"]] isEqualToString:@"10000"]) {
            if (success){
                success(returnDic);
            }
        }
        else {
            if (failure) {
                failure();
            }
            // 判断是否access_token失效
            [self isAccess_tokenSucess:returnDic];
            // 服务器返回失败 统一处理提示 外部不在显示提示
            [self managerWithErrorCode:returnDic];
        }
        
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
        NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode ;
        SVPDismiss
        if (finish) {
            finish();
        }
        if (failure){
            failure();
            NSLog(@"failure statusCode -- %zd,%@", statusCode,error);
        }
        // 网络请求失败 统一提示
        [SVProgressHUD showInfoWithStatus:RXInternetError];
    }];
}

#pragma mark - 统一处理提示信息
+ (void)managerWithErrorCode:(id)responseObject {
    // 提示信息
    NSString *msg = [responseObject objectForKey:@"msg"];
    if (![CommonTTool isBlankString:msg]) {
        [SVProgressHUD showInfoWithStatus:msg];
    }
    else {
        NSInteger code = [[responseObject objectForKey:@"errCode"] integerValue];
        if (code == 1003) {
            [SVProgressHUD showInfoWithStatus:@"参数错误"];
            
            [SVProgressHUD dismissWithDelay:1];
        }
    }
}

#pragma mark - 压缩图片(重画)
+ (UIImage *)imageWithImage:(UIImage*)image scale:(CGFloat)scale {
    CGSize newSize = CGSizeMake(image.size.width*scale, image.size.height*scale);
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark -  压缩图片(系统等比例压缩)
static float scale = 0.4;
+ (NSData *)compactImage:(UIImage *)image {
    NSData * resultData= nil;
    NSData * data = UIImageJPEGRepresentation(image, scale);
    resultData = data;
    while (resultData.length > 1024 * 100 && scale > 0.1) {
        scale -= 0.05;
        UIImage * newImage = [UIImage imageWithData:data];
        NSData * newData = UIImageJPEGRepresentation(newImage, scale);
        resultData = newData;
    }
    return resultData;
}

#pragma mark - 判断token是否失效
+ (void)isAccess_tokenSucess:(NSDictionary *)respos {
    
    if ([[NSString stringWithFormat:@"%@",[respos objectForKey:@"status_code"]] isEqualToString:@"15000"]) {
        [self exitApp];
    } else if ([[NSString stringWithFormat:@"%@",[respos objectForKey:@"code"]] isEqualToString:@"20006"]) {
        if (![[CommonTTool getCurrentVC] isKindOfClass:[LoginVC class]]) {
//            [LEUserManager deleteAllObject]; // 清空所有本地存储数据
            [self exitApp];
        }
    }
}
#pragma mark - 强制更新
+ (void)needUpdateApp {
    
    [CommonTTool queryNewVersionInfo];

    
}

#pragma mark - 退出app
+ (void)exitApp {
//    [LEUserManager deleteAllObject]; // 清空所有本地存储数据
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kisLogin];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserInfo];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserMerchantsInfo];
    [LEUserManager deleteToken];
    UIViewController *currentVC = [CommonTTool getCurrentVC];
    

    
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:@"登录令牌失效" message:@"您的账户在另外一个设备上登录或者登录令牌已过期，请重新登录" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        LoginVC *vc = [[LoginVC alloc] init];
        [[CommonTTool getCurrentVC].navigationController pushViewController:vc animated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:kUserInfoDetailsExitUpDate object:nil];
    }];
    [alterController addAction:sureAction];
    [currentVC presentViewController:alterController animated:YES completion:nil];
}

@end
